import {
  ElMessage,
  type FormInstance,
  type FormRules,
  type MessageParamsWithType,
} from "element-plus";
import { ref, reactive, getCurrentInstance } from "vue";
import { useRouter } from "vue-router";
import bcrypt from 'bcryptjs'

export function useLogin() {
  const loginRuleFormRef = ref<FormInstance>();
  const { proxy }: any = getCurrentInstance();
  const router = useRouter();
  const loginForm = reactive({
    userName: "",
    userPass: "",
  });
  const validateUser = (rule: any, value: any, callback: any) => {
    if (value.trim() === "") {
      callback(new Error("请输入账号"));
    } else {
      callback();
    }
  };
  const validatePass = (rule: any, value: any, callback: any) => {
    if (value.trim() === "") {
      callback(new Error("请输入密码"));
    } else {
      callback();
    }
  };
  const loginRules = reactive<FormRules>({
    userName: [{ validator: validateUser, trigger: "blur" }],
    userPass: [{ validator: validatePass, trigger: "blur" }],
  });
  // 登录提交
  const onSubmit = async (formEl: FormInstance | undefined) => {
    if (!formEl) return;
    await formEl.validate((valid) => {
      if (!valid) return;
      proxy.$http
        .post("/auth/login", loginForm)
        .then((res: any) => {
          if (res.data.role != "user") {
            ElMessage.error("非用户禁止登录");
          } else {
            ElMessage.success(res.message);
            window.sessionStorage.setItem("Infos", JSON.stringify(res.data));
            window.sessionStorage.setItem("token", JSON.stringify(res.token));
            router.push("/userhome");
          }
        })
        .catch((err: any) => {
          ElMessage.error(err.response.data.message);
          formEl.resetFields();
        });
    });
  };

  // 管理员登录提交
  const adminOnSubmit = async (formEl: FormInstance | undefined) => {
    if (!formEl) return;
    await formEl.validate((valid) => {
      if (!valid) return;
      proxy.$http
        .post("/auth/login", loginForm)
        .then((res: any) => {
          if (res.data.role != "admin") {
            ElMessage.error("非管理员禁止登录");
          } else {
            ElMessage.success(res.message);
            window.sessionStorage.setItem("adminInfos", JSON.stringify(res.data));
            window.sessionStorage.setItem("token", JSON.stringify(res.token));
            router.push("/admin");
          }
        })
        .catch((err: any) => {
          ElMessage.error(err.response.data.message);
          formEl.resetFields();
        });
    });
  };

  return {
    router,
    proxy,
    loginForm,
    loginRuleFormRef,
    loginRules,
    onSubmit,
    adminOnSubmit,
    bcrypt
  };
}
